package com.getan.boot.web.trace;

import com.getan.boot.common.holder.trace.TraceContextHolder;
import com.getan.boot.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 设置traceId
 *
 * @author Bruce.Gong
 * @since 1.0.0-SNAPSHOT
 */
@Slf4j
public class TraceContextFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String traceId = request.getHeader("traceId");
        if (StringUtils.isEmpty(traceId)) {
            traceId = StringUtils.uuid();
        }
        TraceContextHolder.setTraceId(traceId);
        filterChain.doFilter(request, response);
        TraceContextHolder.clearTraceId();
    }

    @Override
    public void destroy() {
        super.destroy();
    }
}
